//
//  LBMPictureSelectorController.swift
//  微博
//
//  Created by 刘保满 on 16/5/29.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import HMImagePicker
//定义重用标识符
private let PictureCellId = "PictureCellId"
//定义显示图片的信息
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
private let maxImageCount = 9
private let itemWidth: CGFloat = (ScreenWidth - (colCount + 1) * margin) / colCount

class LBMPictureSelectorController: UICollectionViewController {
    
    
    
    //定义图片的数组
    lazy var images: [UIImage] = [UIImage]()
    //定义选择图片的数组
    lazy var selecteAsset: [PHAsset] = [PHAsset]()

    init() {
        let layout = UICollectionViewFlowLayout()
        //设置itemsize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //设置行间距
        layout.minimumLineSpacing = margin
        //设置列间距
        layout.minimumInteritemSpacing = margin
        //设置每组的内边距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        super.init(collectionViewLayout: layout)
        //设置背景颜色
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        //注册
        self.collectionView?.registerClass(LBMPictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//数据源方法
extension LBMPictureSelectorController {
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = images.count == maxImageCount ? 0 : 1
      
        return images.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! LBMPictureSelectorCell
        
        
        cell.backgroundColor = randomColor()
        if indexPath.item == images.count {
            print(indexPath.item)
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
        }
        //设置代理
        cell.selectorDelegate = self
        
        return cell
        
        
    }
    
}

//扩展LBMPictureSeletorController,继承cell类的协议
extension LBMPictureSelectorController: LBMPictureSelectorCellDelegate {
    
    //实现协议方法
    //添加图片
    func userWillAddPicture() {
        print("添加图片")
        //使用系统的图片选择器
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            print("您没有访问权限")
            return
        }
        
        //MARK:应用第三方框架,修改系统的图片选择器,实现可以选择多张图片的功能
        let picker = HMImagePickerController(selectedAssets: selecteAsset)
        //设置图片选择器的代理
        picker.pickerDelegate = self
        //设置目标图片的大小
        picker.targetSize = CGSize(width: 600, height: 600)
        //设置最大图片选取数
        picker.maxPickerCount = maxImageCount
        
        //跳转控制器
        presentViewController(picker, animated: true, completion: nil)
        
 
//      //MARK:系统的图片选择器
//        let picker = UIImagePickerController()
//        //设置图片选择器的代理
//        picker.delegate = self
//        
//        self.presentViewController(picker, animated: true, completion: nil)
//        
    }
    //删除图片
    func userWillDeletePicture(cell: LBMPictureSelectorCell) {
        
        print("删除图片")
        guard let indexPath = collectionView?.indexPathForCell(cell) else {
            return
        }
        
        //获取cell对应的indexPath
        //删除数组中对应的数据
        images.removeAtIndex(indexPath.item)
        //刷新数据
        collectionView?.reloadData()
        
        
    }
    
    
    
}

//遵守第三方矿建图片选择器的协议
extension LBMPictureSelectorController: HMImagePickerControllerDelegate {
    
    func  imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        self.images = images
        //记录选中的图片
        self.selecteAsset = selectedAssets!
        //刷新
        self.collectionView?.reloadData()
        //跳转
        self.dismissViewControllerAnimated(true, completion: nil)
 
    }
}


//
////遵守图片选择器的协议
//extension LBMPictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
//    
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        //把选择的图片保存到用来存放图片的数组
//        images.append(image)
//        //刷新collectionview
//        self.collectionView?.reloadData()
//        
//        //实现了协议方法之后,视图控制器不会自动跳转回来
//        dismissViewControllerAnimated(true, completion: nil)
//        
//    }
//    
//    
//    
//}





//定义cell类的协议
@objc protocol LBMPictureSelectorCellDelegate: NSObjectProtocol {
    
    //定义可选的协议方法
    optional func userWillAddPicture()
    
    optional func userWillDeletePicture(cell: LBMPictureSelectorCell)
    
}

//定义一个cell 的类
class LBMPictureSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            
            deleteBtn.hidden = image == nil
            ///给按钮设置图片
            addBtn.setImage(image, forState: .Normal)
            
            
        }
    }
    

    //定义代理对象属性
    weak var selectorDelegate: LBMPictureSelectorCellDelegate?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    //默认报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置界面
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) in
            
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
            
        }
        
        //添加按钮点击事件
        addBtn.addTarget(self, action: #selector(LBMPictureSelectorCell.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(LBMPictureSelectorCell.deleteBtnDidClick), forControlEvents: .TouchUpInside)
        
        
    }
    
    //MARK: 按钮点击事件
    @objc private func addBtnDidClick() {
        if image != nil {
            
            return
        }
        //        print("添加")
        //让代理干活
        selectorDelegate?.userWillAddPicture?()
    }
    
    @objc private func deleteBtnDidClick() {
        
        //        print("删除")
        selectorDelegate?.userWillDeletePicture?(self)
        
    }
    
    
    
    //懒加载子控件
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        //        btn.imageView?.contentMode = .ScaleAspectFill
        //        btn.imageView?.clipsToBounds = true
        
        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        
        return btn
    }()
    
    
}














